package com.qd.panda.api;

import cn.hutool.crypto.digest.DigestAlgorithm;
import com.cdqidi.annotation.JumpResponseAnnotation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.common.sys.domain.entity.log.SendLogDTO;
import com.qd.panda.gas.station.req.StationDetailReqDTO;
import com.qd.panda.gas.station.shell.config.ShellConfig;
import com.qd.panda.gas.station.shell.last.LastShellHttpServiceImpl;
import com.qd.panda.gas.station.shell.resp.last.GasStationDTO;
import com.qd.panda.gas.sync.LastShellSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 接收壳牌推送信息
 * 包含退款和停车场价格变化后的数据
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/api/v1/")
@Slf4j
public class LastShellController {
    private final ObjectMapper objectMapper;
    private final LastShellSyncService lastShellSyncService;
    private final LastShellHttpServiceImpl lastShellHttpService;
    @Resource
    private ShellConfig shellConfig;
    /**
     * 退款
     */
    private static final int TYPE_REFUND = 1;
    /**
     * 停车场信息
     */
    private static final int TYPE_PARK = 2;

    @JumpResponseAnnotation
    @PostMapping(value = "/shell/sync")
    public ObjectNode sync(@RequestBody String json) {
        ObjectNode resp = objectMapper.createObjectNode();
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            String partnerId = Optional.ofNullable(jsonNode.get("partnerId")).map(JsonNode::textValue).orElse(null);
            Long timestamp = Optional.ofNullable(jsonNode.get("timestamp")).map(JsonNode::longValue).orElse(null);
            String sign = Optional.ofNullable(jsonNode.get("sign")).map(JsonNode::textValue).orElse(null);
            String stationIds = Optional.ofNullable(jsonNode.get("station_ids")).map(JsonNode::textValue).orElse(null);
            if (!StringUtils.hasLength(partnerId)) {
                resp.put("code", 500);
                resp.put("message", "partnerId为空");
                return resp;
            }
            if (null == timestamp) {
                resp.put("code", 500);
                resp.put("message", "timestamp为空");
                return resp;
            }
            if (!StringUtils.hasLength(sign)) {
                resp.put("code", 500);
                resp.put("message", "sign为空");
                return resp;
            }
            log.info("json: {}", jsonNode);
            Map<String, Object> params = objectMapper.readValue(jsonNode.toString(), new TypeReference<>() {
            });
            params.remove("sign");
            String newSign = cn.hutool.crypto.SecureUtil.signParams(DigestAlgorithm.MD5, params, "&", "=", true, shellConfig.getNormalSecurity());
            boolean b = newSign.equals(sign);
            log.info("壳牌回调,收到的签名: {},自己签名: {},是否一致: {}", sign, newSign, b);
//            if (!SpringContextHolder.getActiveProfile().equals(SpringContextHolder.PROFILE_DEV)) {
//                if (!b) {
//                    resp.put("code", 500);
//                    resp.put("message", "签名不一致");
//                    return resp;
//                }
//            }
            if (StringUtils.hasLength(stationIds)) {
                String[] stationIdsArray = stationIds.split(",");
                List<GasStationDTO> addUpdatelist = new ArrayList<>();
                List<String> deletelist = new ArrayList<>();
                for (String stationId : stationIdsArray) {
                    GasStationDTO gasStationDTO = lastShellHttpService.getStationsById(new StationDetailReqDTO().setStationId(stationId).setSendLog(new SendLogDTO()));
                    if (null == gasStationDTO) {
                        deletelist.add(stationId);
                    } else {
                        addUpdatelist.add(gasStationDTO);
                    }
                }
                if (!addUpdatelist.isEmpty()) {
                    lastShellSyncService.sync(addUpdatelist, false);
                    addUpdatelist.clear();
                }
                if (!deletelist.isEmpty()) {
                    lastShellSyncService.removeByStationIds(deletelist);
                    deletelist.clear();
                }
            }
        } catch (Exception e) {
            log.error("壳牌回调,数据异常,json: {}", json, e);
        }
        resp.put("code", 200);
        resp.put("message", "ok");
        return resp;
    }
}
